package com.auto.autoapp.ui.activity

import android.content.Intent
import android.graphics.Rect
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityLiveMemberPrivateMsgBinding
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.widgets.SimpleToolbar
import com.auto.autoapp.widgets.SettingItemView
import com.auto.autoapp.model.LiveMemberPrivateMsgSetting
import com.auto.autoapp.services.FloatingWindowService
import com.auto.autoapp.task.LiveMemberPMTask
import com.auto.autoapp.task.WatchVideoCommentTask
import com.ven.assists.stepper.StepImpl
import com.ven.assists.stepper.StepManager


class LiveMemberPrivateMsgActivity : BaseActivity() {
    private lateinit var binding: ActivityLiveMemberPrivateMsgBinding
    override fun provideView(): View {
        binding = ActivityLiveMemberPrivateMsgBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle(intent.getStringExtra("title"))
    }

    override fun onInit() {
        // 填充已保存值（聚合对象）
        val live = SpUtil.getLivePMSetting()
        binding.sivWaitSeconds.setValues(listOf(live.waitSeconds.toString()))
        binding.sivSpeakKeywords.setValues(listOf(live.speakKeywords))
        binding.sivLiveList.setValues(live.liveList)
        binding.sivPmList.setValues(live.replyList)
        binding.sivCollectCount.setValues(listOf(live.collectCount.toString()))

        // 焦点滚动适配
        attachFocusScroll(binding.sivWaitSeconds)
        attachFocusScroll(binding.sivSpeakKeywords)

        // 确认保存
        binding.btnConfirm.setOnClickListener {
            val waitStr = binding.sivWaitSeconds.getValues().firstOrNull()?.trim().orEmpty()
            val speakKw = binding.sivSpeakKeywords.getValues().firstOrNull()?.trim().orEmpty()

            // 清除旧错误
            clearError(binding.sivWaitSeconds)
            clearError(binding.sivSpeakKeywords)
            clearError(binding.sivLiveList)
            clearError(binding.sivPmList)

            var hasError = false
            val waitSeconds = waitStr.toIntOrNull()
            if (waitSeconds == null || waitSeconds <= 0) {
                binding.sivWaitSeconds.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入大于0的整数秒数"
                hasError = true
            }
            if (speakKw.isBlank()) {
                binding.sivSpeakKeywords.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请输入关键字"
                hasError = true
            }

            if (hasError) {
                Toast.makeText(this, "请修正标红项后再确认", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val setting = LiveMemberPrivateMsgSetting(
                waitSeconds = waitSeconds!!,
                speakKeywords = speakKw,
                liveList = binding.sivLiveList.getValues(),
                replyList = binding.sivPmList.getValues(),
                collectCount = binding.sivCollectCount.getValues().firstOrNull()?.toIntOrNull()
                    ?: 10
            )
            SpUtil.setLivePMSetting(setting)

            if (FloatingWindowService.getInstance() == null) {
                val intent = Intent(this, FloatingWindowService::class.java)
                intent.action = "SHOW_FLOATING_WINDOW"
                startService(intent)
            }

            StepManager.isStop = true
            StepManager.execute(LiveMemberPMTask::class.java, 1, begin = true)
        }
    }

    private fun clearError(item: SettingItemView) {
        item.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error = null
    }

    private fun attachFocusScroll(item: SettingItemView) {
        item.setOnChildFocusListener { target ->
            scrollToView(target)
        }
    }

    private fun scrollToView(target: View) {
        binding.scrollContent.post {
            val rect = Rect()
            target.getDrawingRect(rect)
            binding.scrollContent.offsetDescendantRectToMyCoords(target, rect)
            val y = (rect.top - dp(24)).coerceAtLeast(0)
            binding.scrollContent.smoothScrollTo(0, y)
        }
    }

    private fun dp(value: Int): Int {
        val d = resources.displayMetrics.density
        return (value * d).toInt()
    }
}